package com.sdygmedia.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;


public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	@Resource
	private SessionFactory sessionFacory;
	private Class<T> clazz;
	
	public BaseDaoImpl() {
		// ͨ利用反射获取实例的真实类型
		ParameterizedType pt = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0];

		//System.out.println("---> clazz = " + clazz);
	}

	protected Session getSession() {
		return sessionFacory.getCurrentSession();
	}

	@Override
	public void save(Object entity) {
		getSession().save(entity);

	}

	@Override
	public void delete(long id) {
		
		T entity = (T) getById(id);
		if (entity != null) {
			getSession().delete(entity);
		}
	}

	@Override
	public T update(Object entity) {
		getSession().update(entity);
		return null;
	}

	@Override
	public T getById(long id) {
		T entity = (T) getSession().get(clazz, id);
		return entity;
	}

	/**
	 * 存在一些问题，暂时不用此方法
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<T> getByIds(long[] ids) {
		return getSession()//
				.createQuery(
						"FROM " + clazz.getSimpleName() + " WHERE id IN (:ids)")//
				// .setParameters(Long, ids)//
				.list();//

	}

	@Override
	public List findAll() {
		//System.out.println(getSession().createQuery("FROM " + clazz.getSimpleName()).list());
		//System.out.println("FROM " + clazz.getSimpleName());
		return getSession().createQuery("FROM " + clazz.getSimpleName()).list();
	}

	public SessionFactory getSessionFacory() {
		return sessionFacory;
	}

	public void setSessionFacory(SessionFactory sessionFacory) {
		this.sessionFacory = sessionFacory;
	}

}
